// 需要文件控件 #file-3,  文件上传后台uploadFiles，form（#upload）， csrf组件name="csrfmiddlewaretoken"
// 检测按钮#detectSeeds
// 手机相机选项#isPhoneCap
// 文件上传组件，以及检测种子按钮事件
const MAX_FILES_DETECT = 5;
$("#file-3").fileinput({ //文件上传插件
	language: 'zh', //设置语言,
	theme: 'fa5',
	uploadUrl: '../uploadFiles',
	enableResumableUpload: false, //设置false有问题，要改name
	maxFileCount: MAX_FILES_DETECT,
	maxTotalFileCount: MAX_FILES_DETECT,
	validateInitialCount: true,
	overwriteInitial: false,
	maxFileSize: 10240,
	minFileSize: 10,
	showUpload: true,
	showRemove: true,
	showCaption: false,
	showRotate: false,
	browseClass: "btn btn-primary",
	uploadClass: "btn btn-primary",
	browseIcon: '',
	removeIcon: '',
	uploadIcon: '',
	allowedFileExtensions: ["jpg", 'jpeg', "png", "gif"],
	allowedFileTypes: ['image'],
	allowedPreviewTypes: ['image'],
	fileType: "image",
	//previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
	removeLabel: "删除全部",
	uploadLabel: "上传全部",
	browseLabel: "选取图片",
	previewFileType: "image",
	//dropZoneEnabled: false,
	dropZoneTitle: "请选择本地文件或手机拍照<br/>最多一次上传与检测5张图片",
	showDescriptionClose: false,
	msgFileNotReadable: '图片文件 "{name}" 不能打开！',
	msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
	msgDuplicateFile: '文件 "{name}" of same size "{size} KB" 被重复选择，请重新选择.',
	uploadExtraData: function() {
		let csrf = $('#upload input[name="csrfmiddlewaretoken"]').val();
		return {
			'csrfmiddlewaretoken': csrf
		}
	},
	slugCallback: function(text) { //取消设置括号的转换

		return isEmpty(text) ? '' : String(text)
	},
	resumableUploadOptions: {
		fallback: null,
		testUrl: null, // used for checking status of chunks/ files previously / partially uploaded
		chunkSize: 10240, // in KB
		maxThreads: 4,
		maxRetries: 3,
		showErrorLog: true,
		retainErrorHistory: false, // when set to true, display complete error history always unless user explicitly resets upload
		skipErrorsAndProceed: false // when set to true, files with errors will be skipped and upload will continue with other files
	},
}).on('filebatchuploadcomplete', function() {
	$('#detectSeeds').css('visibility', 'visible') //可见
	$('#main div.theme-fa5>span button.fileinput-remove').removeClass('fileinput-remove-button') //删除按钮
}).on('fileimagesloaded', function(event) {
	$('#detectSeeds').css('visibility', 'hidden') //隐藏
}).on("fileclear", function(event, data, msg) {
	$('#detectSeeds').css('visibility', 'hidden') //隐藏
	$('#main div.theme-fa5>span button.fileinput-remove').addClass('fileinput-remove-button') //删除按钮
});

// .on('change', function(event) {
// 	console.log('changing..........')
// }).on('fileselect', function(event, numFiles, label) {
//     console.log("fileselect", numFiles, label);
// });;;


$('div.theme-fa5>span').prependTo($('div.theme-fa5')) //调整按钮位置,注意元素的位置


$('#isPhoneCap').insertAfter($('div.btn-file')).find('#chkPhoneCap').change(function() { //控制手机拍照（对应复选按钮）
	$camera = document.querySelector("#file-3");
	if (this.checked == true) {
		$camera.setAttribute("capture", "user");
	} else {
		$camera.removeAttribute("capture");
	}
});

$('#detectSeeds').insertAfter($('#isPhoneCap')).after($('#pending-pa')); //检测按钮的位置

function isEmpty(value) {
	if (value === undefined || value === null || value === '') {
		return true;
	}
	if (Object.prototype.toString.call(value) === '[object String]') {
		return value.trim() === '';
	}
	return false;
}

$(function() {
	$('#detectSeeds').click(function() { //种子检测按钮事件
		let fileCount = $('#file-3').fileinput('getFilesCount')
		let imageNum = $(
				'div.file-preview-frame div.kv-file-content img.file-preview-image.kv-preview-data')
			.length
		console.log('fileCount:', fileCount, '--imageNum', imageNum)
		if (fileCount > 0 || imageNum == 0) { //没有上传图片
			bootbox.alert({
				title: "有问题",
				message: "还有图片没有上传！",
				size: 'small'
			});
			this.style.visibility = 'hidden'
		} else {
			let data = []
			let images = $(
				'div.file-preview div.file-preview-success > div.kv-file-content img.file-preview-image'
			)
			if (images.length > MAX_FILES_DETECT)
			{
				bootbox.alert({
					title: "请检查",
					message: `种子检测图片个数多于${MAX_FILES_DETECT}个，<br/>请检查上传图片数量再进行！`,
					size: 'small'
				});
				return
			}
			
			images.each(function() {
				data.push({
					fileName: this.title,
					width: this.naturalWidth,
					height: this.naturalHeight,
				});
			})
			//console.log('---准备提交', data)

			let csrf = $('#upload input[name="csrfmiddlewaretoken"]').val();
			let action = $('#choseAction input[name="action"]:checked').val();
			console.log('提交方式', action);

			let dataForm = new FormData()
			dataForm.append('csrfmiddlewaretoken', csrf)
			dataForm.append('batch_data', JSON.stringify(data));
			dataForm.append('action', action);
			console.log(dataForm.get('batch_data'))

			$('#pending').show();
			axios.post('../batchDetect', dataForm)
				.then(function(response) {
					let batchResult = response.data;

					console.log('------', batchResult)
					if (batchResult.statusCode != '404') {
						window.g_batch = { //全局
							data: batchResult.data,
							index: 0
						}

						bootbox.alert({
							title: "检测成果",
							message: "种子图片检测结果成功！",
							size: 'small'
						});

						SaveResultImages(); //保存检测的图片step1
						setResultByIndex(0); //设置显示结果step2						
						showAllPageLinks(); //设置翻页页码！step3
						//还有一些出错处理要解决


						$('#a_detect').tab('show');
						console.log('1222222222222222222222')
						//showCanvasBoxNumber()//step4
					}
				})
				.catch(function(error) {
					bootbox.alert({
						title: "错误",
						message: "有未知错误，请刷新后重试",
						size: 'small'
					});
					console.log(error);
				})
				.finally(() => {
					$('#pending').hide();
				});
		}
	});

});


//通过全局g_batch，切换显示结果
function setResultByIndex(ind) {
	window.g_batch.index = ind
	let result = window.g_batch.data[ind]
	window.g_data = result; //保存全局变量，复杂的JSON对象
	showData(result); //显示检测结果

	showImageOnCanvas(); //显示第一张图片
	showCanvasBoxNumber(); //显示相应的Box与空间
}
// 保存检测结果对应的图片img
function SaveResultImages() {
	//let images = $('div.file-preview div.file-preview-success > div.kv-file-content img.file-preview-image')
	//$('#saveImages').empty().append(images.clone());//、
	let images = $('div.file-preview div.file-preview-success > div.kv-file-content img.file-preview-image')

	let llen = window.g_batch.data.length
	if (images.length != llen) {
		console.log('error in images length and JSON return')
	}
	for (let i = 0; i < llen; i++) {
		let image = images[i].cloneNode();

		window.g_batch.data[i].imageSrc = image;
	}
}

function showCanvasBoxNumber() {
	document.querySelector('#drawRect').click(); //触发显示图片与boxes
	document.querySelector('#alertShow').style.display = ''; //显示提示
	document.querySelector("#labelNumber").checked = false;
	document.querySelector("#labelShow").checked = true;
}

function showImageOnCanvas() { //显示图片，清空box
	let img = window.g_data.imageSrc

	const $canvas = document.querySelector("#show")
	const context = $canvas.getContext("2d");
	$canvas.width = img.naturalWidth;
	$canvas.height = img.naturalHeight;

	$('#spinner').show(); //显示进度条
	context.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);

	let $canvasBox = document.querySelector("#showBox");
	$canvasBox.width = img.naturalWidth;
	$canvasBox.height = img.naturalHeight;
	let ctx = $canvasBox.getContext("2d");
	ctx.clearRect(0, 0, img.naturalWidth, img.naturalHeight);

	$('#spinner').hide();
	console.log(img.naturalWidth, img.naturalHeight);
}

function clearCanvas() { //清掉Canva
	const $canvas = document.querySelector("#show")
	const context = $canvas.getContext("2d");
	context.clearRect(0, 0, $canvas.width, $canvas.height);

	let $canvasBox = document.querySelector("#showBox");
	let ctx = $canvasBox.getContext("2d");
	ctx.clearRect(0, 0, $canvasBox.width, $canvasBox.height);
}
